#encoding:utf8
import os , json , types , re
import tornado.web
from handlers import *

from framework.inc import ReturnHelper
from framework.py_ex import * 

from configs import *


'''{
	msg_update_chk 		--检查版本更新
    req-->>{
        tag = [tagname]%
        base={...},
        body={
            binver = xx,
            srcver = xx
        }
    }

    rep<<--{
        r    = svrstatu,
        err  = r!=0 then '',
        data = {
            ret    = 0,
            tarver  = 1.0,
            reslist = {}
        }

    }
}
'''

class updateverHandler(tornado.web.RequestHandler):
    
    _verdata = dict()
    
    # def initialize(self):
    #     file_data = ConfigUpdate.VER_FILE
    #     logging.info("updateHandler initialize!")
    #     self._verdata = reader_ex.readJsonFile(file_data)
    

    @gameDecorator.post_api_chk
    def post(self , ret , apiname , rcv_dict):   
        if not ret:
            func = self.__getattribute__(apiname)
            if apiname == "msg_update_chk":
                ret = func(rcv_dict["base"]["pid"] ,rcv_dict["base"]["vb"] ,rcv_dict["base"]["vs"]) 
            

        self.write(json.dumps(ret))

#======================================================================================
    #float clientver      
    def msg_update_chk(self , platid, binver , srcver):

        #todo
        platname = "heyshell"
        # platname = ConfigPlat.PLAT[platid]       

        cfgupdate = ConfigUpdate.VERLIST[platname]

        binint = FuncCommon.getVerInt(binver)
        srcint = int(srcver)

        svr_binmin = FuncCommon.getVerInt(cfgupdate["minbinver"])
        svr_binnew = FuncCommon.getVerInt(cfgupdate["newvinber"])
        svr_srcmin = int(cfgupdate["minsrcver"])
        svr_srcnew = int(cfgupdate["newsrcver"])

        repdic = dict(
            ret = None,
            restlist = {},
            downurl = '',
            newbinver = cfgupdate["newvinber"],
            newsrcver = cfgupdate["newsrcver"]
            )
        ret = None

        #bin < min? Must down another
        if (binint < svr_binmin):
            ret = 1
            repdic["downurl"] = "baidu.com"
        else:
            #src < min ? hotupdate
            if srcint < svr_srcmin:
                ret = 2
                # todo不同平台更新不同的文件 
                # 暂时只支持一种平台 
                staticpath = os.path.join(os.getcwd(), "static")
                jsonfile = staticpath + os.sep + "hex" + os.sep + str(binver) + os.sep + str(svr_srcnew) + os.sep + "ver.data"
                verlist = reader_ex.readJsonFile(jsonfile)
                
                repdic["reslist"] = verlist
            else:
                #go on play
                ret = 0
        repdic["ret"] = ret 

        return ReturnHelper.ret(repdic)
